package com.lxp.userms.controller;

import com.lxp.userms.entity.User;
import com.lxp.userms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    @GetMapping("/register")
    public String showRegisterPage() {
        return "register";
    }

    @PostMapping("/register")
    public String register(User user) {
        userService.register(user);
        return "redirect:/user/login";
    }

    @GetMapping("/login")
    public String showLoginPage() {
        return "login";
    }

    @PostMapping("/login")
    public String login(String username, String password, Model model, HttpSession session) {
        User user = userService.login(username, password);
        if (user != null) {
            session.setAttribute("user", user); // 将用户信息存储在会话中
            model.addAttribute("user", user);
            switch (user.getRole()) {
                case 0: // 普通用户
                    return "user/dashboard";
                case 1: // 专家用户
                    return "expert/dashboard";
                case 2: // 管理员
                    return "admin/dashboard";
                default:
                    return "login";
            }
        } else {
            model.addAttribute("error", "用户名或密码错误！");
            return "login";
        }
    }

    @GetMapping("/profile")
    public String showProfile(int id, Model model) {
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "profile";
    }

    @PostMapping("/update")
    public String update(User user) {
        userService.updateUser(user);
        return "redirect:/user/profile?id=" + user.getId();
    }

    @GetMapping("/forgot-password")
    public String showForgotPasswordPage() {
        return "forgot_password";
    }

    @PostMapping("/forgot-password")
    public String forgotPassword(String email, Model model) {
        // 实现密码找回逻辑，如发送重置密码邮件
        model.addAttribute("message", "密码重置链接已发送到您的邮箱！");
        return "forgot_password";
    }

    @GetMapping("/list")
    public String userList(Model model) {
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        return "user_list";
    }

    @GetMapping("/delete")
    public String deleteUser(int id) {
        userService.deleteUser(id);
        return "redirect:/user/list";
    }
}